<template>
  <div class="activation-code-list-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>激活码列表</span>
          <div class="header-buttons">
            <el-button type="success" @click="showDirectExportDialog"
              >批量导出</el-button
            >
            <el-button type="primary" @click="handleGenerateCodes"
              >生成激活码</el-button
            >
          </div>
        </div>
      </template>
      <div class="search-box">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="激活码">
            <el-input
              v-model="queryParams.code"
              placeholder="请输入激活码"
              clearable
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option label="未使用" :value="0" />
              <el-option label="已使用" :value="1" />
              <el-option label="已过期" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="可用次数">
            <el-input-number
              v-model="queryParams.usage_count"
              placeholder="请输入次数"
              :min="0"
              clearable
              @clear="() => (queryParams.usage_count = undefined)"
            />
          </el-form-item>
          <el-form-item label="复制状态">
            <el-select
              v-model="queryParams.is_copied"
              placeholder="是否已复制"
              clearable
            >
              <el-option label="未复制" :value="0" />
              <el-option label="已复制" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="导出状态">
            <el-select
              v-model="queryParams.is_exported"
              placeholder="是否已导出"
              clearable
            >
              <el-option label="未导出" :value="0" />
              <el-option label="已导出" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 批量操作按钮 -->
      <div class="batch-actions" v-if="multipleSelection.length > 0">
        <el-button type="primary" @click="handleBatchCopy">批量复制</el-button>
        <el-button type="success" @click="showExportDialog">批量导出</el-button>
        <el-button type="warning" @click="handleBatchMarkCopied"
          >标记为已复制</el-button
        >
        <el-button type="info" @click="handleBatchMarkExported"
          >标记为已导出</el-button
        >
        <span class="selection-count"
          >已选择 {{ multipleSelection.length }} 项</span
        >
      </div>

      <el-table
        v-loading="loading"
        :data="sortedCodeList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="code" label="激活码" width="200">
          <template #default="scope">
            <div class="code-cell">
              <span>{{
                userStore.isTest ? maskCode(scope.row.code) : scope.row.code
              }}</span>
              <el-button
                size="small"
                type="primary"
                link
                @click="handleCopyCode(scope.row)"
              >
                复制
              </el-button>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="photo_url" label="图片" width="100">
          <template #default="scope">
            <el-image 
              v-if="scope.row.photo_url" 
              :src="scope.row.photo_url" 
              class="thumbnail-image"
              :preview-src-list="[scope.row.photo_url]"
              preview-teleported
              fit="cover"
            />
            <span v-else>无图片</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="usage_count" label="使用次数" width="100" />
        <!-- <el-table-column prop="days" label="有效天数" /> -->
        <el-table-column prop="create_time" label="创建时间" width="180" />
        <el-table-column prop="used_time" label="使用时间" width="180">
          <template #default="scope">
            {{ scope.row.used_at || "未使用" }}
          </template>
        </el-table-column>
        <el-table-column prop="used_by" label="使用用户">
          <template #default="scope">
            {{ scope.row.used_by || "无" }}
          </template>
        </el-table-column>
        <el-table-column prop="expire_time" label="过期时间" width="180" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="复制/导出" width="120">
          <template #default="scope">
            <div class="tag-group">
              <el-tag
                v-if="scope.row.is_copied"
                size="small"
                type="success"
                effect="plain"
              >
                已复制
              </el-tag>
              <el-tag v-else size="small" type="info" effect="plain">
                未复制
              </el-tag>
              <el-tag
                v-if="scope.row.is_exported"
                size="small"
                type="success"
                effect="plain"
              >
                已导出
              </el-tag>
              <el-tag v-else size="small" type="info" effect="plain">
                未导出
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleCopyCode(scope.row)"
            >
              复制
            </el-button>
            <el-button
              size="small"
              type="success"
              @click="handleExportCode(scope.row)"
            >
              导出
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              :disabled="scope.row.status !== 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="queryParams.page"
          :page-size="queryParams.limit"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 导出设置弹窗 -->
    <el-dialog title="导出设置" v-model="exportDialogVisible" width="500px">
      <el-form :model="exportSettings" label-width="120px">
        <el-form-item label="导出类型">
          <el-radio-group v-model="exportSettings.exportType">
            <el-radio label="selected">导出选中项</el-radio>
            <el-radio label="limit">限制导出数量</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="按使用次数筛选">
          <el-switch v-model="exportSettings.filterByUsageCount" />
        </el-form-item>

        <el-form-item label="使用次数" v-if="exportSettings.filterByUsageCount">
          <div class="usage-count-row">
            <el-input-number
              v-model="exportSettings.usageCount"
              :min="0"
              :max="100"
              placeholder="请输入次数"
              @change="updateUsageCountInfo"
            />
            <el-tag type="info" style="margin-left: 10px">
              剩余：{{ filteredByUsageCount }} 个
            </el-tag>
          </div>
        </el-form-item>

        <el-form-item
          label="导出数量"
          v-if="exportSettings.exportType === 'limit'"
        >
          <div class="usage-count-row">
            <el-input-number
              v-model="exportSettings.exportCount"
              :min="1"
              :max="1000"
              placeholder="请输入导出数量"
            />
            <el-tag
              type="warning"
              style="margin-left: 10px"
              v-if="exportSettings.exportCount > availableExportCount"
            >
              超出可用数量
            </el-tag>
          </div>
        </el-form-item>

        <el-form-item label="激活码状态">
          <el-select
            v-model="exportSettings.codeStatus"
            placeholder="请选择状态"
            style="width: 100%"
            @change="updateUsageCountInfo"
          >
            <el-option label="全部" value="all" />
            <el-option label="仅未使用" value="unused" />
            <el-option label="仅已使用" value="used" />
          </el-select>
        </el-form-item>

        <el-form-item label="剩余激活码">
          <el-tag type="info"
            >当前剩余未使用激活码: {{ remainingCodesCount }}</el-tag
          >
        </el-form-item>

        <el-divider content-position="center">导出预览</el-divider>

        <div class="export-summary">
          <div class="summary-item">
            <span class="summary-label">导出状态:</span>
            <span class="summary-value">{{ getExportStatusText() }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">可导出数量:</span>
            <span class="summary-value">{{ availableExportCount }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">实际导出数量:</span>
            <span class="summary-value">{{ getActualExportCount() }}</span>
          </div>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="exportDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleBatchExport"
            :disabled="getActualExportCount() === 0"
            >确认导出</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 直接批量导出弹窗 -->
    <el-dialog
      title="批量导出激活码"
      v-model="directExportDialogVisible"
      width="550px"
    >
      <el-form :model="directExportSettings" label-width="150px">
        <el-form-item label="激活码状态">
          <el-select
            v-model="directExportSettings.codeStatus"
            placeholder="请选择状态"
            style="width: 100%"
            @change="updateDirectExportStats"
          >
            <el-option label="全部" value="all" />
            <el-option label="仅未使用" value="unused" />
            <el-option label="仅已使用" value="used" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否已复制">
          <el-switch
            v-model="directExportSettings.isCopy"
            @change="updateDirectExportStats"
          />
        </el-form-item>
        <el-form-item label="是否已导出">
          <el-switch
            v-model="directExportSettings.is_exported"
            @change="updateDirectExportStats"
          />
        </el-form-item>
        <el-form-item label="指定代理">
          <el-select
            v-model="directExportSettings.agency"
            placeholder="请选择指定代理"
            style="width: 100%"
            @change="updateDirectExportStats"
          >
            <el-option
              v-for="agent in agentList"
              :key="agent.id"
              :label="agent.name"
              :value="agent.id"
              label="全部"
              value="all"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="按使用次数筛选">
          <el-switch
            v-model="directExportSettings.filterByUsageCount"
            @change="updateDirectExportStats"
          />
        </el-form-item>

        <el-form-item
          label="使用次数"
          v-if="directExportSettings.filterByUsageCount"
        >
          <div class="usage-count-row">
            <el-input-number
              v-model="directExportSettings.usageCount"
              :min="0"
              :max="100000"
              placeholder="请输入次数"
              @change="updateDirectExportStats"
            />
            <el-tag type="info" style="margin-left: 10px">
              可用：{{ availableByUsageCount }} 个
            </el-tag>
          </div>
        </el-form-item>

        <el-form-item label="导出数量">
          <div class="usage-count-row">
            <el-input-number
              v-model="directExportSettings.exportCount"
              :min="1"
              :max="directAvailableCount || 1000"
              placeholder="请输入导出数量"
            />
            <el-tag
              type="success"
              style="margin-left: 10px"
              v-if="directExportSettings.exportCount <= directAvailableCount"
            >
              {{
                Math.max(
                  directAvailableCount - directExportSettings.exportCount,
                  0
                )
              }}
              个将保留
            </el-tag>
            <el-tag type="warning" style="margin-left: 10px" v-else>
              超出可用数量
            </el-tag>
          </div>
        </el-form-item>

        <el-divider content-position="center">导出预览</el-divider>

        <div class="export-summary">
          <div class="summary-item">
            <span class="summary-label">筛选条件:</span>
            <span class="summary-value">{{ getDirectExportFilterText() }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">可导出数量:</span>
            <span class="summary-value">{{ directAvailableCount }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">实际导出数量:</span>
            <span class="summary-value">{{ getDirectExportCount() }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">导出后剩余:</span>
            <span class="summary-value">{{
              Math.max(directAvailableCount - getDirectExportCount(), 0)
            }}</span>
          </div>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="directExportDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleDirectExport"
            :disabled="getDirectExportCount() === 0"
          >
            确认导出 ({{ getDirectExportCount() }} 个)
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { getAgentList } from "@/api/agents";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getActivationCodeList,
  deleteActivationCode,
  markActivationCodeCopied,
  markActivationCodeExported,
  batchMarkActivationCodesCopied,
  batchMarkActivationCodesExported,
  getActivationCodeStats,
  getActivationCodesToExport,
} from "@/api/activation-codes";
import { useUserStore } from "@/store/user";

const agentList = ref([]);
const router = useRouter();
const userStore = useUserStore();
const loading = ref(false);
const codeList = ref([]);
const total = ref(0);
const multipleSelection = ref([]);

// 导出相关
const exportDialogVisible = ref(false);
const exportSettings = reactive({
  exportType: "selected", // selected=选中项, limit=限制数量
  exportCount: 10,
  codeStatus: "all", // all=全部, unused=未使用, used=已使用
  filterByUsageCount: false,
  usageCount: 0,
});

// 直接导出相关
const directExportDialogVisible = ref(false);
const directExportSettings = reactive({
  exportCount: 100,
  codeStatus: "unused", // 默认导出未使用的激活码
  filterByUsageCount: false,
  usageCount: 0,
  agency: "", // 指定代理ID
  isCopy: false, // 是否已复制
});
const directAvailableCount = ref(0);
const availableByUsageCount = ref(0); // 特定使用次数的可用激活码数

// 计算剩余未使用的激活码数量
const remainingCodesCount = computed(() => {
  return codeList.value.filter((item) => item.status === 0).length;
});

// 根据使用次数筛选后的激活码数量
const filteredByUsageCount = ref(0);

// 可用于导出的激活码数量(根据所有筛选条件)
const availableExportCount = computed(() => {
  let filteredCodes = [...multipleSelection.value];

  // 按状态筛选
  if (exportSettings.codeStatus === "unused") {
    filteredCodes = filteredCodes.filter((item) => item.status === 0);
  } else if (exportSettings.codeStatus === "used") {
    filteredCodes = filteredCodes.filter((item) => item.status === 1);
  }

  // 按使用次数筛选
  if (exportSettings.filterByUsageCount) {
    filteredCodes = filteredCodes.filter(
      (item) => item.usage_count === exportSettings.usageCount
    );
  }

  return filteredCodes.length;
});

// 获取代理列表
const getAgent = async () => {
  loading.value = true;
  try {
    const res = await getAgentList(queryParams);
    if (res.code === 0) {
      agentList.value = res.data.items || [];
    } else {
      ElMessage.error(res.message || "获取代理列表失败");
    }
  } catch (error) {
    console.error("获取代理列表失败", error);
    ElMessage.error("获取代理列表失败");
  } finally {
    loading.value = false;
  }
};

// 更新使用次数筛选信息
const updateUsageCountInfo = () => {
  // 计算指定使用次数的激活码数量
  let count = 0;

  // 从选中项中统计
  if (multipleSelection.value.length > 0) {
    let filteredCodes = [...multipleSelection.value];

    // 应用状态筛选
    if (exportSettings.codeStatus === "unused") {
      filteredCodes = filteredCodes.filter((item) => item.status === 0);
    } else if (exportSettings.codeStatus === "used") {
      filteredCodes = filteredCodes.filter((item) => item.status === 1);
    }

    // 应用使用次数筛选
    count = filteredCodes.filter(
      (item) => item.usage_count === exportSettings.usageCount
    ).length;
  }

  filteredByUsageCount.value = count;
};

// 更新直接导出的统计信息
const updateDirectExportStats = async () => {
  try {
    // 构建查询参数
    const params = {
      status:
        directExportSettings.codeStatus === "unused"
          ? 0
          : directExportSettings.codeStatus === "used"
          ? 1
          : "",
    };

    if (directExportSettings.filterByUsageCount) {
      params.usage_count = directExportSettings.usageCount;
    }

    // 获取匹配的激活码数量
    const res = await getActivationCodeStats(params);
    if (res.code === 0) {
      directAvailableCount.value = res.data.total || 0;
      availableByUsageCount.value = directExportSettings.filterByUsageCount
        ? res.data.total || 0
        : res.data.usage_count_stats?.[directExportSettings.usageCount] || 0;
    }
  } catch (error) {
    console.error("获取激活码统计失败", error);
  }
};

// 获取导出状态文本
const getExportStatusText = () => {
  if (multipleSelection.value.length === 0) {
    return "未选择激活码";
  }

  let statusText = [];

  if (exportSettings.codeStatus === "unused") {
    statusText.push("未使用");
  } else if (exportSettings.codeStatus === "used") {
    statusText.push("已使用");
  } else {
    statusText.push("全部状态");
  }

  if (exportSettings.filterByUsageCount) {
    statusText.push(`${exportSettings.usageCount}次激活码`);
  }

  return statusText.join("的");
};

// 获取直接导出的筛选条件文本
const getDirectExportFilterText = () => {
  let statusText = [];

  if (directExportSettings.codeStatus === "unused") {
    statusText.push("未使用");
  } else if (directExportSettings.codeStatus === "used") {
    statusText.push("已使用");
  } else {
    statusText.push("全部状态");
  }

  if (directExportSettings.filterByUsageCount) {
    statusText.push(`使用次数为${directExportSettings.usageCount}次`);
  }

  return statusText.join("、");
};

// 获取实际要导出的激活码数量
const getActualExportCount = () => {
  const available = availableExportCount.value;

  if (available === 0) {
    return 0;
  }

  if (exportSettings.exportType === "limit") {
    return Math.min(exportSettings.exportCount, available);
  }

  return available;
};

// 获取直接导出的实际数量
const getDirectExportCount = () => {
  if (directAvailableCount.value === 0) {
    return 0;
  }

  return Math.min(directExportSettings.exportCount, directAvailableCount.value);
};

// 显示直接导出对话框
const showDirectExportDialog = async () => {
  // 初始化直接导出数据
  await updateDirectExportStats();
  directExportDialogVisible.value = true;
};

const queryParams = reactive({
  page: 1,
  limit: 10,
  code: "",
  status: "",
  usage_count: undefined,
  is_copied: "",
  is_exported: "",
});

// 对列表进行排序，未导出和未复制的排在前面
const sortedCodeList = computed(() => {
  if (!codeList.value || codeList.value.length === 0) return [];

  return [...codeList.value].sort((a, b) => {
    // 首先按照导出状态排序（未导出的排前面）
    if (!a.is_exported && b.is_exported) return -1;
    if (a.is_exported && !b.is_exported) return 1;

    // 然后按照复制状态排序（未复制的排前面）
    if (!a.is_copied && b.is_copied) return -1;
    if (a.is_copied && !b.is_copied) return 1;

    // 最后按照ID降序排序（新创建的排前面）
    return b.id - a.id;
  });
});

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection;
};

// 获取激活码列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await getActivationCodeList(queryParams);
    if (res.code === 0) {
      codeList.value = res.data.items;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.message || "获取激活码列表失败");
    }
  } catch (error) {
    console.error("获取激活码列表失败", error);
    ElMessage.error("获取激活码列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 0:
      return "success";
    case 1:
      return "info";
    case 2:
      return "danger";
    default:
      return "info";
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0:
      return "未使用";
    case 1:
      return "已使用";
    case 2:
      return "已过期";
    default:
      return "未知";
  }
};

// 对激活码进行打码处理
const maskCode = (code) => {
  if (!code) return "";
  // 只显示前3位和后2位，其余用*代替
  const prefix = code.substring(0, 3);
  const suffix = code.substring(code.length - 2);
  const maskedPart = "*".repeat(code.length - 5);
  return `${prefix}${maskedPart}${suffix}`;
};

// 处理复制激活码
const handleCopyCode = async (row) => {
  try {
    // 测试账号只能复制打码后的激活码
    const codeToCopy = userStore.isTest ? maskCode(row.code) : row.code;

    // 复制激活码
    await copyCode(codeToCopy);

    // 如果未标记为已复制，则标记
    if (!row.is_copied && !userStore.isTest) {
      // 测试账号不能标记激活码状态
      const res = await markActivationCodeCopied(row.id);
      if (res.code === 0) {
        // 更新本地数据
        row.is_copied = true;
        row.copied_time = new Date().toISOString();
        ElMessage.success("已标记为已复制");
      }
    }
  } catch (error) {
    console.error("复制或标记失败", error);
  }
};

// 复制激活码
const copyCode = (code) => {
  return navigator.clipboard
    .writeText(code)
    .then(() => {
      ElMessage.success("复制成功");
    })
    .catch(() => {
      ElMessage.error("复制失败");
    });
};

// 处理导出激活码
const handleExportCode = async (row) => {
  try {
    // 导出为CSV
    exportCodeToCSV([row]);

    // 如果未标记为已导出，则标记
    if (!row.is_exported && !userStore.isTest) {
      // 测试账号不能标记激活码状态
      const res = await markActivationCodeExported(row.id);
      if (res.code === 0) {
        // 更新本地数据
        row.is_exported = true;
        row.exported_time = new Date().toISOString();
        ElMessage.success("已标记为已导出");
      }
    }
  } catch (error) {
    console.error("导出或标记失败", error);
  }
};

// 将激活码导出为CSV
const exportCodeToCSV = (codes) => {
  if (!codes || codes.length === 0) return;

  let csvContent = "激活码,状态,使用次数,创建时间,过期时间,备注\n";
  codes.forEach((item) => {
    // 测试账号只能导出打码后的激活码
    const codeToExport = userStore.isTest ? maskCode(item.code) : item.code;
    csvContent += `${codeToExport},${getStatusText(item.status)},${
      item.usage_count || 0
    },${item.created_at || ""},${item.expire_at || ""},${item.remark || ""}\n`;
  });

  const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
  const link = document.createElement("a");
  const url = URL.createObjectURL(blob);

  link.setAttribute("href", url);
  link.setAttribute("download", `激活码_${new Date().getTime()}.csv`);
  link.style.visibility = "hidden";

  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);

  ElMessage.success(`成功导出${codes.length}个激活码`);
};

// 显示导出设置对话框
const showExportDialog = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择要导出的激活码");
    return;
  }

  // 重置导出设置中的可用数量统计
  updateUsageCountInfo();

  exportDialogVisible.value = true;
};

// 批量导出激活码
const handleBatchExport = async () => {
  if (
    multipleSelection.value.length === 0 &&
    exportSettings.exportType === "selected"
  ) {
    ElMessage.warning("请选择要导出的激活码");
    return;
  }

  try {
    // 根据导出设置过滤需要导出的激活码
    let codesToExport = [];

    // 根据状态过滤
    let filteredCodes = [...multipleSelection.value];
    if (exportSettings.codeStatus === "unused") {
      filteredCodes = filteredCodes.filter((item) => item.status === 0);
    } else if (exportSettings.codeStatus === "used") {
      filteredCodes = filteredCodes.filter((item) => item.status === 1);
    }

    // 根据使用次数筛选
    if (exportSettings.filterByUsageCount) {
      filteredCodes = filteredCodes.filter(
        (item) => item.usage_count === exportSettings.usageCount
      );
    }

    // 根据导出类型决定导出数量
    if (exportSettings.exportType === "selected") {
      codesToExport = filteredCodes;
    } else if (exportSettings.exportType === "limit") {
      codesToExport = filteredCodes.slice(0, exportSettings.exportCount);
    }

    // 检查是否有可导出的激活码
    if (codesToExport.length === 0) {
      ElMessage.warning("没有符合条件的激活码可导出");
      return;
    }

    // 导出为CSV
    exportCodeToCSV(codesToExport);

    // 获取未标记为已导出的ID列表
    const unexportedIds = codesToExport
      .filter((item) => !item.is_exported)
      .map((item) => item.id);

    if (unexportedIds.length > 0 && !userStore.isTest) {
      // 测试账号不能标记激活码状态
      // 批量标记为已导出
      const res = await batchMarkActivationCodesExported(unexportedIds);
      if (res.code === 0) {
        // 更新本地数据
        multipleSelection.value.forEach((item) => {
          if (unexportedIds.includes(item.id)) {
            item.is_exported = true;
            item.exported_time = new Date().toISOString();
          }
        });
        ElMessage.success(`已标记${unexportedIds.length}个激活码为已导出`);
      }
    }

    // 关闭弹窗
    exportDialogVisible.value = false;
  } catch (error) {
    console.error("批量导出或标记失败", error);
    ElMessage.error("批量导出失败");
  }
};

// 批量复制激活码
const handleBatchCopy = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择要复制的激活码");
    return;
  }

  // 将选中的激活码组合成文本
  const codes = multipleSelection.value
    .map((item) => {
      // 测试账号只能复制打码后的激活码
      return userStore.isTest ? maskCode(item.code) : item.code;
    })
    .join("\n");

  try {
    // 复制到剪贴板
    await navigator.clipboard.writeText(codes);
    ElMessage.success(`成功复制${multipleSelection.value.length}个激活码`);

    // 获取未标记为已复制的ID列表
    const uncopiedIds = multipleSelection.value
      .filter((item) => !item.is_copied)
      .map((item) => item.id);

    if (uncopiedIds.length > 0 && !userStore.isTest) {
      // 测试账号不能标记激活码状态
      // 批量标记为已复制
      const res = await batchMarkActivationCodesCopied(uncopiedIds);
      if (res.code === 0) {
        // 更新本地数据
        multipleSelection.value.forEach((item) => {
          if (uncopiedIds.includes(item.id)) {
            item.is_copied = true;
            item.copied_time = new Date().toISOString();
          }
        });
        ElMessage.success(`已标记${uncopiedIds.length}个激活码为已复制`);
      }
    }
  } catch (error) {
    console.error("批量复制或标记失败", error);
    ElMessage.error("批量复制失败");
  }
};

// 批量标记为已复制
const handleBatchMarkCopied = async () => {
  // 检查权限
  if (userStore.isTest && !userStore.hasPermission("edit:activation_code")) {
    ElMessage.warning("测试账号不能修改激活码状态");
    return;
  }

  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择要标记的激活码");
    return;
  }

  // 获取未标记为已复制的ID列表
  const uncopiedIds = multipleSelection.value
    .filter((item) => !item.is_copied)
    .map((item) => item.id);

  if (uncopiedIds.length === 0) {
    ElMessage.info("选中的激活码已全部标记为已复制");
    return;
  }

  try {
    // 批量标记为已复制
    const res = await batchMarkActivationCodesCopied(uncopiedIds);
    if (res.code === 0) {
      // 更新本地数据
      multipleSelection.value.forEach((item) => {
        if (uncopiedIds.includes(item.id)) {
          item.is_copied = true;
          item.copied_time = new Date().toISOString();
        }
      });
      ElMessage.success(`已标记${uncopiedIds.length}个激活码为已复制`);
    }
  } catch (error) {
    console.error("批量标记失败", error);
    ElMessage.error("批量标记失败");
  }
};

// 批量标记为已导出
const handleBatchMarkExported = async () => {
  // 检查权限
  if (userStore.isTest && !userStore.hasPermission("edit:activation_code")) {
    ElMessage.warning("测试账号不能修改激活码状态");
    return;
  }

  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择要标记的激活码");
    return;
  }

  // 获取未标记为已导出的ID列表
  const unexportedIds = multipleSelection.value
    .filter((item) => !item.is_exported)
    .map((item) => item.id);

  if (unexportedIds.length === 0) {
    ElMessage.info("选中的激活码已全部标记为已导出");
    return;
  }

  try {
    // 批量标记为已导出
    const res = await batchMarkActivationCodesExported(unexportedIds);
    if (res.code === 0) {
      // 更新本地数据
      multipleSelection.value.forEach((item) => {
        if (unexportedIds.includes(item.id)) {
          item.is_exported = true;
          item.exported_time = new Date().toISOString();
        }
      });
      ElMessage.success(`已标记${unexportedIds.length}个激活码为已导出`);
    }
  } catch (error) {
    console.error("批量标记失败", error);
    ElMessage.error("批量标记失败");
  }
};

// 查询
const handleQuery = () => {
  queryParams.page = 1;
  getList();
};

// 重置查询
const resetQuery = () => {
  queryParams.page = 1;
  queryParams.code = "";
  queryParams.status = "";
  queryParams.usage_count = undefined;
  queryParams.is_copied = "";
  queryParams.is_exported = "";
  handleQuery(); // 确保调用正确的查询函数
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.page = val;
  getList();
};

// 每页条数改变
const handleSizeChange = (val) => {
  queryParams.limit = val;
  queryParams.page = 1;
  getList();
};

// 生成激活码
const handleGenerateCodes = () => {
  // 检查权限
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能生成激活码");
    return;
  }

  router.push("/activation-code/generate");
};

// 删除激活码
const handleDelete = (row) => {
  // 检查权限
  if (userStore.isTest && !userStore.hasPermission("delete:activation_code")) {
    ElMessage.warning("测试账号不能删除激活码");
    return;
  }

  ElMessageBox.confirm(`确认要删除激活码 ${row.code} 吗?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await deleteActivationCode(row.id);
        if (res.code === 0) {
          ElMessage.success("删除成功");
          getList();
        } else {
          ElMessage.error(res.message || "删除失败");
        }
      } catch (error) {
        console.error("删除失败", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 处理直接批量导出
const handleDirectExport = async () => {
  try {
    loading.value = true;

    if (directExportSettings.agency) {
      // 如果指定了代理，确保代理ID有效
      if (
        !agentList.value.some(
          (agent) => agent.id === directExportSettings.agency
        )
      ) {
        ElMessage.error("指定的代理无效");
        loading.value = false;
        return;
      }
    } else {
      ElMessage.error("选择指定代理无效");
      return;
    }

    // 构建查询参数
    const params = {
      status:
        directExportSettings.codeStatus === "unused"
          ? 0
          : directExportSettings.codeStatus === "used"
          ? 1
          : "",
      created_by: directExportSettings.agency,
      is_copied: directExportSettings.isCopy ? 1 : 0,
      is_exported: directExportSettings.is_exported ? 1 : 0,
      limit: directExportSettings.exportCount,
    };

    if (directExportSettings.filterByUsageCount) {
      params.usage_count = directExportSettings.usageCount;
    }

    // 获取要导出的激活码
    const res = await getActivationCodesToExport(params);
    if (res.code === 0 && res.data && res.data.items) {
      const codesToExport = res.data.items;

      // 检查是否有可导出的激活码
      if (codesToExport.length === 0) {
        ElMessage.warning("没有符合条件的激活码可导出");
        loading.value = false;
        return;
      }

      // 导出为CSV
      exportCodeToCSV(codesToExport);

      // 获取未标记为已导出的ID列表
      const unexportedIds = codesToExport
        .filter((item) => !item.is_exported)
        .map((item) => item.id);

      if (unexportedIds.length > 0 && !userStore.isTest) {
        // 测试账号不能标记激活码状态
        // 批量标记为已导出
        const markRes = await batchMarkActivationCodesExported(unexportedIds);
        if (markRes.code === 0) {
          ElMessage.success(`已标记${unexportedIds.length}个激活码为已导出`);
        }
      }

      // 关闭弹窗
      directExportDialogVisible.value = false;

      // 更新列表数据
      getList();
    } else {
      ElMessage.error(res.message || "导出失败");
    }
  } catch (error) {
    console.error("批量导出失败", error);
    ElMessage.error("批量导出失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getList();
  getAgent();
});
</script>

<style scoped>
.activation-code-list-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header-buttons {
  display: flex;
  gap: 10px;
}
.search-box {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.code-cell {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.thumbnail-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
}
.tag-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}
.batch-actions {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}
.selection-count {
  margin-left: auto;
  color: #606266;
  font-size: 14px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
.usage-count-row {
  display: flex;
  align-items: center;
}
.export-summary {
  margin-top: 20px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.summary-label {
  font-weight: bold;
}
.summary-value {
  margin-left: 10px;
}
</style>
